/*
 * DesignAssignment01.asm
 *
 *  Created: 2/11/2014 3:05:05 PM
 *   Author: Matt
 */ 
 
 ;INITSTACK 
 LDI R16,HIGH(RAMEND) 
 OUT SPH,R16 
 LDI R16,LOW(RAMEND) 
 OUT SPL,R16 

 ldi r16, 30	//Start number
 ldi r17, 1		//decrement amount
 ldi r18, 20	//Total numbers, must be even
 ldi r19, 4		//increment num amount
 ldi r22, 5		//increment num amount2
StoreNums:
 add r16, r19	//add 4 to the previous number
 push r16		//store value into ram
 sub r18, r17	//decrement counter
 add r16, r22	//add 5 to the previous number
 push r16		//store value into ram
 sub r18, r17	//decrement counter
 breq Stage2	//branch when counter=0
 rjmp StoreNums	//loop to stack more numbers

Stage2:
 ldi r18, 20	//total numbers
 ldi r19, 3		//subtract with this register
 ldi r22, 5		//subtract with this register
 ldi r20, 0		//3s total low
 ldi r21, 0		//3s total high 
 ldi r23, 0		//3s total low
 ldi r24, 0		//5s total high
getNums:
 pop r16		//grab number from stack
 mov r25, r16	//place number into temp holder
ChkDivBy3:
 sub r25, r19	//temp-3
 brpl ChkDivBy3	//if temp>=0, go back to subtraction
 add r25, r19	//temp+3, -> check for zero
 breq addTo3s	//if temp=0, move to add to 3s total
 rjmp Start5	//move to check for division by 5
 
addTo3s:
 add r20, r16	//add value to 3s total
 in r26, SREG	//grab carry bit from status reg
 sbrs r26, 0	//check if there is a carry
 rjmp Start5	//if no carry, mmove on
 inc r21		//add carry bit to high 3s total
 
Start5:
 mov r25, r16	//create temp reg
ChkDivBy5:
 sub r25, r22	//temp-5
 brpl ChkDivBy5	//if temp>=0, go back to subtraction
 add r25, r22	//temp+5, -> check for zero
 breq addTo5s	//if temp=0, move to add to 5s total
 rjmp ifDone	//move to check for division by 5
 
addTo5s:
 add r23, r16	//add value to 5s total
 in r26, SREG	//grab carry bit from status reg
 sbrs r26, 0	//check if there is a carry
 rjmp ifDone	//if no carry, mmove on
 inc r24		//add carry bit to high 5s total

ifDone:
 sub r18, r17	//decrement counter
 brne getNums

done: rjmp done	//complete